<template>
  <view>
    <view v-if="!userId">
      <inner-login></inner-login>
    </view>
    <view v-else>
      <view class="custom-page flex_p">
        <uv-form ref="form" :model="form" :rules="rules" labelWidth="110px" errorType="border-bottom">
          <uv-form-item label="询价标题" borderBottom required prop="orderXjName">
            <uv-input v-model="form.orderXjName" border="none" input-align="right" placeholder="请输入询价标题"></uv-input>
          </uv-form-item>
          <uv-form-item label="询价内容" label-position="top" prop="orderXjRemark">
            <view class="flex_h_8"></view>
            <uv-textarea v-model="form.orderXjRemark" placeholder="请输入询价标题"></uv-textarea>
          </uv-form-item>
          <uv-form-item label="联系人" prop="name" borderBottom required>
            <uv-input v-model="form.name" placeholder="请输入联系人" :disabled="permission != 0" disabledColor="transparent" input-align="right" border="none" />
          </uv-form-item>
          <uv-form-item label="联系方式" prop="phone" borderBottom required>
            <uv-input v-model="form.phone" placeholder="请输入联系方式" disabled disabledColor="transparent" input-align="right" border="none" />
          </uv-form-item>
          <uv-form-item label="询价图片" borderBottom>
            <view class="flex_1 flex flex_x_end">
              <view style="width: 180rpx;">
                <uv-upload
                    :fileList="fileList1"
                    name="1"
                    :maxCount="1"
                    @afterRead="afterRead"
                    @delete="deletePic"
                ></uv-upload>
              </view>
            </view>
          </uv-form-item>
          <uv-form-item label="询价文件" borderBottom>
            <view class="flex_1 flex flex_x_end">
              <view style="width: 180rpx;">
                <uv-upload
                    :fileList="fileList2"
                    name="2"
                    accept="all"
                    :maxCount="1"
                    @afterRead="afterReadOther"
                    @delete="deletePicOther"
                ></uv-upload>
              </view>
            </view>
          </uv-form-item>
        </uv-form>
      </view>
      <view class="flex_h_50"></view>
      <view class="flex_1 flex_p_lr">
        <uv-button type="primary" color="#2D4C98" shape="circle" @click="submitForm">确认提交</uv-button>
      </view>
    </view>
  </view>
</template>

<script>

import {getToken, getUserInfoId} from "@/utils/auth";
import config from "@/config";
import UserInfoApi from "@/api/system/userInfo";
import ProductApi from "@/api/product";
import InnerLogin from "@/components/innerLogin.vue";

export default {
  components: {
    InnerLogin
  },
  data() {
    return {
      baseURL: config.baseUrl,
      fileList1: [],
      fileList2: [],
      upImg: [],
      upFiles: [],
      userId: null,
      permission: null,
      form: {
        name: null,
        phone: null,
        companyName: null,
        orderXjName: null,
        orderXjRemark: null,
        orderXjVideo: null,
        orderXjImg: null,
        orderXjFiles: null,
        productId: null,
      },
      rules: {
        orderXjName: [
          {required: true, message: "请输入询价标题", trigger: "blur"},
        ],
        name: [
          {required: true, message: "请输入联系人", trigger: "blur"},
        ],
        phone: [
          {required: true, message: "请输入联系方式", trigger: "blur"},
        ],
      }
    };
  },
  onShow() {
    this.userId = getUserInfoId();
    if (this.userId) {
      this.getUserInfo();
    }
  },
  methods: {
    async getUserInfo() {
      const data = await UserInfoApi.getUserProfile(this.userId);
      this.user = data?.data;
      this.form.name = this.user.name;
      this.form.phone = this.user.phone;
      this.form.companyName = this.user.companyName;
      const otherData = await UserInfoApi.getUserPermission();
      this.permission = otherData?.data;
    },

    async afterRead(event) {
      // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
      let lists = [].concat(event.file)
      let fileListLen = this[`fileList${event.name}`].length
      lists.map((item) => {
        this[`fileList${event.name}`].push({
          ...item,
          status: 'uploading',
          message: '上传中'
        })
      })
      for (let i = 0; i < lists.length; i++) {
        const result = await this.uploadFilePromise(lists[i],'image')
        let item = this[`fileList${event.name}`][fileListLen]
        this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
          status: 'success',
          message: '',
          url: result
        }))
        fileListLen++
      }
    },
    uploadFilePromise(file, type) {
      const _this = this
      return new Promise((resolve, reject) => {
        let a = uni.uploadFile({
          header: {
            'Authorization': 'Bearer ' + getToken(),
          },
          url: _this.baseURL + '/resource/oss/upload',
          filePath: file.url,
          name: 'file',
          formData: {
            file: file
          },
          success: (res) => {
            setTimeout(() => {
              resolve(res.data.data)
              const json = JSON.parse(res.data);
              console.log('6666---->>>,',json);
              if (type === 'image') {
                this.upImg.push(json.data?.ossId);
              }else {
                this.upFiles.push(json.data?.ossId);
              }
            }, 1000)
          }
        });
      })
    },
    // 删除图片
    deletePic(event) {
      this[`fileList${event.name}`].splice(event.index, 1);
    },
    async afterReadOther(event) {
      // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
      let lists = [].concat(event.file)
      let fileListLen = this[`fileList${event.name}`].length
      lists.map((item) => {
        this[`fileList${event.name}`].push({
          ...item,
          status: 'success',
          message: '上传中'
        })
      })
      for (let i = 0; i < lists.length; i++) {
        const result = await this.uploadFilePromise(lists[i],'other')
        let item = this[`fileList${event.name}`][fileListLen]
        this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
          status: 'success',
          message: '',
          url: result
        }))
        fileListLen++
      }
    },
    deletePicOther(event) {
      this[`fileList${event.name}`].splice(event.index, 1);
    },
    submitForm() {
      if (this.upImg.length > 0) {
        this.form.orderXjImg = this.upImg.join(',');
      }
      if (this.upFiles.length > 0) {
        this.form.orderXjFiles = this.upFiles.join(',');
      }
      this.$refs.form.validate().then(() => {
        if (this.form.productId) {
          this.form.type = 0;
        }else {
          this.form.type = 1;
        }
        ProductApi.getProductConsult(this.form).then(() => {
          uni.showToast({
            title: '提交成功',
            icon: 'success',
            duration: 2000,
          });
          setTimeout(() => {
            uni.switchTab({
              url: '/pages/index'
            })
          },2000)
        });
      });
    },
  },
}
</script>
<style>

</style>
<style scoped lang="scss">
.custom-page{
}
</style>
